import { createRouter, createWebHistory } from 'vue-router';
import LoginRegister from '../views/LoginRegister.vue';
import ProductList from '../views/ProductList.vue';
import ProductDetail from '../views/ProductDetail.vue';
import CreateProduct from '../views/CreateProduct.vue';
import CreateInvitation from "@/views/CreateInvitation.vue";
import InvitationList from "@/views/InvitationList.vue";
import InvitationDetail from "@/views/InvitationDetail.vue";
import EditInvitation from "@/views/EditInvitation.vue";

const routes = [
    {
        path: '/',
        name: 'Home',
        redirect: '/products' // 默认跳转到商品列表
    },
    {
        path: '/login',
        name: 'LoginRegister',
        component: LoginRegister
    },
    {
        path: '/products',
        name: 'ProductList',
        component: ProductList
    },
    {
        path: '/product/:id',
        name: 'ProductDetail',
        component: ProductDetail,
        props: true
    },
    {
        path: '/create-product',
        name: 'CreateProduct',
        component: CreateProduct
    },
    {
        path: '/create-invitation',
        name: 'CreateInvitation',
        component: CreateInvitation,
        meta: { requiresAuth: true }
    },
    {
        path: '/invitations',
        name: 'InvitationList',
        component: InvitationList
    },
    {
        path: '/invitation/:id',
        name: 'InvitationDetail',
        component: InvitationDetail,
        props: true
    },
    {
        path: '/edit-invitation/:id',
        name: 'EditInvitation',
        component: EditInvitation,
        props: true,
        meta: { requiresAuth: true }
    }
];

const router = createRouter({
    history: createWebHistory(),
    routes
});

// 路由守卫，检查登录状态
router.beforeEach((to, from, next) => {
    // 需要登录的页面 - 只有创建和编辑功能需要登录
    const authRequired = ['CreateProduct', 'CreateInvitation', 'EditInvitation'];
    const isLoggedIn = localStorage.getItem('isLogin') === 'true';

    if (authRequired.includes(to.name) && !isLoggedIn) {
        next('/login');
    } else {
        next();
    }
});

export default router;